package com.wish233.wiliwilivideo.utils;

import com.wish233.wiliwilicommon.common.ErrorCode;
import com.wish233.wiliwilicommon.exception.BusinessException;
import com.wish233.wiliwilivideo.mapper.VideoMapper;
import org.apache.ibatis.cursor.Cursor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author WHH
 * 布隆过滤器工具类
 */
@Component
public class BloomFilterUtils {

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private VideoMapper videoMapper;
    private RBloomFilter<String> bloomFilter;
    @Resource
    private PlatformTransactionManager transactionManager;

    @PostConstruct
    public void init() {
        bloomFilter = redissonClient.getBloomFilter("wiliwiliBloomFilter");
        bloomFilter.tryInit(100000L, 0.01);
        //将数据库数据传入
        TransactionTemplate transactionTemplate =
                new TransactionTemplate(transactionManager);
        transactionTemplate.execute(status -> {
            try (Cursor<Long> cursor = videoMapper.getAllIdsStream();) {
                cursor.forEach(id -> bloomFilter.add(id.toString()));
            } catch (IOException e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
            }
            return null;
        });
    }

    public void add(String key) {
        bloomFilter.add(key);
    }

    public boolean contains(String key) {
        return bloomFilter.contains(key);
    }
}